package com.chinawlx.wlxteacher.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.utils.WLXConstant;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.widget.silidingmenu.RoundImageView;
import com.chinawlx.wlxteacher.wlx_student;
import com.chinawlx.wlxteacher.wlx_studentDao;
import com.chinawlx.wlxteacher.wlx_student_order_detail;
import com.chinawlx.wlxteacher.wlx_student_order_detailDao;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者:黄帅
 * 时间:16/9/17
 * 描述: 选择停课学员,选择加课学员
 */
public class WLXChooseStudentActivity extends WLXBaseActivity {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_ok)
    TextView mTvOk;
    @BindView(R.id.et_student_search)
    EditText mEtStudentSearch;
    @BindView(R.id.tv_choose_all)
    TextView mTvChooseAll;
    @BindView(R.id.lv_students)
    ListView mLvStudents;

    public static final String STUDENT_ID = "STUDENT_ID";
    public static final String STUDENT_NAME = "STUDENT_NAME";

    private ArrayList<StudentInfoBean> infos = new ArrayList<>();
    private StudentAdapter mStudentAdapter;
    private List<wlx_student_order_detail> mOrderDetails;
    private boolean mChooseAll = false;
    private boolean mHasChecked = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_stop_student);
        ButterKnife.bind(this);
        init();

    }

    //初始化
    private void init() {
        initData();
        initView();
    }

    private void initData() {
        mOrderDetails = WLXGreenDaoUtil.getStudentOrderDetailDao()
                .queryBuilder().where
                        (wlx_student_order_detailDao.Properties.Grade_id.eq(WLXConstant.GRADE_ID)
                        ).list();
        for (wlx_student_order_detail detail :
                mOrderDetails) {
            StudentInfoBean bean = new StudentInfoBean();
            bean.num = detail.getBalance_number();
            bean.student_id = detail.getStudent_id();

            List<wlx_student> students = WLXGreenDaoUtil.getStudentDao().queryBuilder().where
                    (wlx_studentDao.Properties.Student_id.eq(detail.getStudent_id())).list();
            wlx_student student = students.get(0);
            bean.name = student.getRealname() + "";
            bean.icon = student.getAvatar_url() + "";

            infos.add(bean);
        }
    }

    private void initView() {
        mStudentAdapter = new StudentAdapter();
        mStudentAdapter.setData(infos);
        mLvStudents.setAdapter(mStudentAdapter);

        //搜索处理
        handleSearch();
    }

    private void handleSearch() {
        mEtStudentSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                infos.clear();
                if (TextUtils.isEmpty(s)) {
                    initData();
                    mStudentAdapter.setData(infos);
                    mStudentAdapter.notifyDataSetChanged();
                    return;
                }

                for (wlx_student_order_detail detail :
                        mOrderDetails) {
                    StudentInfoBean bean = new StudentInfoBean();
                    bean.num = detail.getBalance_number();
                    bean.student_id = detail.getStudent_id();

                    List<wlx_student> searchList = WLXGreenDaoUtil.getStudentDao().queryBuilder()
                            .where(wlx_studentDao.Properties.Student_id.eq(detail.getStudent_id()))
                            .whereOr(wlx_studentDao.Properties
                                    .Realname_pinyin.like("%" + s + "%"), wlx_studentDao
                                    .Properties.Realname.like("%" + s + "%")).list();
                    if (searchList.size() > 0) {
                        wlx_student student = searchList.get(0);
                        bean.name = student.getRealname();
                        bean.icon = student.getAvatar_url();
                        infos.add(bean);
                    }
                }
                mStudentAdapter.setData(infos);
                mStudentAdapter.notifyDataSetChanged();
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.tv_ok, R.id.tv_choose_all})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                setResult(RESULT_CANCELED);
                finish();
                break;
            case R.id.tv_ok:
                mHasChecked = false;
                Intent intent = new Intent();
                if (mChooseAll) {
                    mHasChecked = true;
                    //选中所有
                    intent.putExtra(STUDENT_ID, -1);
                    String names = "(";
                    int count = 0;
                    for (StudentInfoBean bean :
                            infos) {
                        names += bean.name + ",";

                        count++;
                        if (count >= 3) break;
                    }
                    if (!"(".equals(names)) {

                        names = names.substring(0, names.lastIndexOf(","));
                        names += "等" + infos.size() + "人)";
                        intent.putExtra(STUDENT_NAME, names);
                    }else {
                        intent.putExtra(STUDENT_NAME, " ");
                    }
                } else {
                    for (StudentInfoBean bean :
                            infos) {
                        if (bean.check) {
                            mHasChecked = true;
                            intent.putExtra(STUDENT_ID, bean.student_id);
                            intent.putExtra(STUDENT_NAME, "(" + bean.name + ")");
                        }
                    }
                }
                if (mHasChecked) {
                    setResult(RESULT_OK, intent);
                    finish();
                }
                break;
            case R.id.tv_choose_all:
                mChooseAll = !mChooseAll;//点击之后反选
                mTvChooseAll.setText(mChooseAll ? "撤销" : "全选");
                for (StudentInfoBean bean :
                        infos) {
                    bean.check = mChooseAll;
                }
                mStudentAdapter.setData(infos);
                mStudentAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_CANCELED);
        finish();
    }

    //学生列表
    class StudentAdapter extends BaseAdapter {
        private ArrayList<StudentInfoBean> list = new ArrayList<>();

        public StudentAdapter() {
        }

        public void setData(ArrayList<StudentInfoBean> studentList) {
            this.list = studentList;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(WLXChooseStudentActivity.this, R.layout
                                .item_choose_stuent_info,
                        null);
                holder = new ViewHolder(convertView);

                holder.mIcon = (RoundImageView) convertView.findViewById(R.id
                        .iv_icon_student_info);
                holder.mName = (TextView) convertView.findViewById(R.id.tv_name_student_info);
                holder.mCb = (CheckBox) convertView.findViewById(R.id.cb_choose_student);
                holder.mNum = (TextView) convertView.findViewById(R.id.tv_num_student_info);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            //数据
            final StudentInfoBean info = list.get(position);
            holder.mName.setText(info.name);
            holder.mNum.setText(info.num + "课次");
            Glide.with(WLXChooseStudentActivity.this).load(info.icon
            ).into(holder.mIcon);
            holder.mCb.setChecked(info.check);
            holder.mCb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (StudentInfoBean bean :
                            infos) {
                        bean.check = bean.student_id == info.student_id;
                    }
                    mStudentAdapter.setData(infos);
                    notifyDataSetChanged();
                }
            });
            return convertView;
        }

        class ViewHolder {
            @BindView(R.id.iv_icon_student_info)
            RoundImageView mIcon;
            @BindView(R.id.tv_name_student_info)
            TextView mName;
            @BindView(R.id.tv_num_student_info)
            TextView mNum;
            @BindView(R.id.cb_choose_student)
            CheckBox mCb;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }

    //学生信息bean,保存查询到的学生信息
    class StudentInfoBean {
        int student_id;
        String icon;
        String name;
        int num;
        boolean check;
    }

}
